package initalize

import (
	"RoccBlog/global"
	"RoccBlog/model"
	"RoccBlog/util/constant"
	"context"
	"encoding/json"
	"errors"
	"log"
)

// RefreshCacheValue 刷新缓存值
func RefreshCacheValue() error {
	var list []model.Cache
	err := global.DB.Preload("CacheValue").Find(&list).Error
	if err != nil {
		return errors.New("加载缓存失败" + err.Error())
	}

	//拼接缓存为map形式
	var cacheMap = make(map[string]any)
	for _, cache := range list {
		var m = make(map[string]any)
		for _, value := range cache.CacheValue {
			m[value.Value] = value.Key
		}
		cacheMap[cache.Code] = m
	}

	//存储到redis中
	data, err := json.Marshal(&cacheMap)
	if err != nil {
		return errors.New("加载缓存失败" + err.Error())
	}
	err = global.RedisClient.HSet(context.Background(), constant.GlobalCacheKey, constant.GlobalCommonsCacheKey, data).Err()

	if err != nil {
		return errors.New("加载缓存失败" + err.Error())
	}
	return nil
}

// RefreshDatabaseCache 刷新数据库缓存
func RefreshDatabaseCache() error {
	var list []model.DataCache
	err := global.DB.Find(&list).Error
	if err != nil {
		return errors.New("加载缓存失败" + err.Error())
	}

	cacheMap := make(map[string]any)
	for _, val := range list {

		//1. 执行sql
		rows, err := global.DB.Raw(val.Sql).Rows()
		if err != nil {
			return errors.New("加载缓存失败" + err.Error())
		}
		//2. 将sql添加到map中
		sqlRltMap := make(map[string]any)
		var key, value string
		for rows.Next() {
			rows.Scan(&key, &value)
			sqlRltMap[value] = key
		}

		//3. 将本次查询添加到m中
		cacheMap[val.Code] = sqlRltMap
	}

	data, err := json.Marshal(&cacheMap)
	if err != nil {
		log.Fatalln("加载缓存失败", err.Error())
	}
	err = global.RedisClient.HSet(context.Background(), constant.GlobalCacheKey, constant.GlobalDatabaseCacheKey, data).Err()

	if err != nil {
		log.Fatalln("加载缓存失败", err.Error())
	}
	return nil
}

func RefreshAllCache() {
	if RefreshDatabaseCache() != nil {
		log.Fatalln("初始化database缓存失败")
	}
	if RefreshCacheValue() != nil {
		log.Fatalln("初始化commons缓存失败")
	}
}
